<template>
  <!-- 订单列表 -->
  <div class='app-container'>
    <div class="search">
      <!-- 筛选查询 -->
      <div class="search_top">
        <div class="search_top_left">
          <el-icon>
            <Search />
          </el-icon>
          <span>筛选搜索</span>
        </div>
        <div class="search_top_right">
          <el-button @click="resetSearchForm">重置</el-button>
          <el-button type="primary" @click="getAdminList">查询搜索</el-button>
        </div>
      </div>
      <!-- 表单搜索 -->
      <el-form :inline="true" :model="searchOrderForm" ref="OrderForm" class="demo-form-inline">
        <el-form-item label="输入搜索:" prop="orderSn">
          <el-input v-model="searchOrderForm.orderSn" placeholder="订单编号" clearable />
        </el-form-item>
        <el-form-item label="收货人:" class="peo" prop="receiverKeyword">
          <el-input v-model="searchOrderForm.receiverKeyword" placeholder="收货人姓名/手机号码" clearable />
        </el-form-item>
        <el-form-item label="提交时间:" prop="createTime">
          <el-date-picker v-model="searchOrderForm.createTime" type="date" placeholder="请选择时间" clearable
            value-format="YYYY-MM-DD" />

        </el-form-item>
        <el-form-item label="订单状态:" prop="status">
          <el-select v-model="searchOrderForm.status" placeholder="全部" clearable>
            <el-option label="待付款" value="0" />
            <el-option label="待发货" value="1" />
            <el-option label="已发货" value="2" />
            <el-option label="已完成" value="3" />
            <el-option label="已关闭" value="4" />
            <el-option label="无效订单" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单分类:" prop="orderType">
          <el-select v-model="searchOrderForm.orderType" placeholder="全部" clearable>
            <el-option label="正常订单" value="0" />
            <el-option label="秒杀订单" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单来源:" prop="sourceType">
          <el-select v-model="searchOrderForm.sourceType" placeholder="全部" clearable>
            <el-option label="PC订单" value="0" />
            <el-option label="app订单" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <!-- 数据表格 -->
    <el-table ref="multipleTableRef" :data="tabList" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column property="id" label="编号" show-overflow-tooltip />
      <el-table-column property="orderSn" label="订单编号" show-overflow-tooltip width="200" />
      <el-table-column label="提交时间" show-overflow-tooltip width="200">
        <template #default="{ row }">
          {{ row.createTime ? dayjs(row.createTime).format("YYYY-MM-DD HH:mm:ss") : "" }}
        </template>
      </el-table-column>
      <el-table-column property="memberUsername" label="用户账号" width="120" />
      <el-table-column property="address" label="订单金额" show-overflow-tooltip width="120">
        <template #default="{ row }">
          {{ "￥" + row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column property="address" label="支付方式" show-overflow-tooltip>
        <template #default="{ row }">
          <!-- 0未支付  1支付宝 2微信 -->
          {{ row.payType === 0 ? "未支付" : row.payType === 1 ? "支付宝" : "微信" }}
        </template>
      </el-table-column>
      <el-table-column property="address" label="订单来源" show-overflow-tooltip width="100">
        <template #default="{ row }">
          {{ row.orderType === 0 ? "APP订单" : "未知来源" }}
        </template>
      </el-table-column>
      <el-table-column property="address" label="订单状态" show-overflow-tooltip>
        <template #default="{ row }">
          <!-- 0待付款  1待发货 2已发货 3 4 已关闭-->
          {{ row.status === 0 ? "待付款" : row.status === 1 ? "待发货" : row.status === 2 ? "已发货" : row.status === 4 ? "已关闭" :
            "已完成" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" show-overflow-tooltip fixed="right" width="190">
        <template #default="{ row }">
          <el-button size="small" @click="selectOrder(row.id)">查看订单</el-button>
          <el-button type="danger" v-if="row.status === 4" size="small" @click="deleteOreer(row.id)">删除订单</el-button>
          <el-button v-if="row.status === 0" size="small" @click="closeOrderByIds(row.id)">关闭订单</el-button>
          <el-button v-if="row.status === 2 || row.status === 3" size="small" @click="openOrderTrack()">订单跟踪</el-button>
          <el-button v-if="row.status === 1" size="small"
            @click="sendOrder({ deliveryCompany: row.deliveryCompany, deliverySn: row.deliverySn, orderId: row.id })">订单发货</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pag">
      <!-- 左侧批量操作 -->
      <div class="left_more">
        <el-select v-model="selectValue" class="m-2" placeholder="批量操作" size="large">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button type="primary" @click="selectChange">确定</el-button>

      </div>
      <el-pagination v-model:current-page="paginationParams.currentPage" v-model:page-size="paginationParams.pageSize"
        :page-sizes="[5, 10, 15, 20]" background layout="total, sizes, prev, pager, next, jumper"
        :total="paginationParams.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </div>
  <!-- 关闭订单 -->
  <CloseOrder :orderVisiable="closeOrderVisiable" @closeOrderVisiable="closeOpenOrderVisiable" :orderID="orderId"
    @getOrderDetail="getAdminList" :closeIds="closeIds" />
  <OrderTrach :orderVisiable="orderTrackVis" @closeOrderTrack="closeOrderTrack" :times="times" />
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'
import { ref, watch } from 'vue';
import useTable from "@/hooks/umsTable"
import * as order from "@/request/order"
import { dayjs, ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
// import { closeOrder } from "@/hooks/oms/closeOrder"
import CloseOrder from "./components/closeOrderDlg.vue"
import OrderTrach from "./components/orderTrackDlg.vue"
const router = useRouter()
const searchOrderForm = ref<IOrderFormParamsModel>({
  orderSn: undefined,
  receiverKeyword: "",
  createTime: "",
  status: undefined,
  orderType: undefined,
  sourceType: undefined

})
const { tabList,
  paginationParams,
  handleSizeChange,
  handleCurrentChange,
  getAdminList } = useTable(order.selectOrderItem, searchOrderForm.value)
// 表格选项数据
const multipleSelection = ref([])
// 重置表单
const resetSearchForm = () => {
  searchOrderForm.value.orderSn = undefined;
  searchOrderForm.value.receiverKeyword = "";
  searchOrderForm.value.createTime = "";
  searchOrderForm.value.status = undefined;
  searchOrderForm.value.orderType = undefined;
  searchOrderForm.value.sourceType = undefined;
  paginationParams.currentPage = 1;
  paginationParams.pageSize = 5;
}
// 表格选项变化时触发
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}
// 批量操作
const selectValue = ref()
const closeIds = ref()
// 下拉菜单
const options = [
  {
    value: 1, label: "批量发货"
  },
  {
    value: 2, label: "关闭订单"
  },
  {
    value: 3, label: "删除订单"
  }

]
// 批量操作改变---请求未完成
const selectChange = () => {
  if (selectValue.value === 1) {
    sendOrder(multipleSelection.value)
  } else if (selectValue.value === 2) {
    // 批量关闭订单
    const ids = [] as number[]
    multipleSelection.value.forEach(item => {
      ids.push(item.id)
    })
    closeOrderByIds(ids)
  } else if (selectValue.value === 3) {
    const ids = [] as number[]
    multipleSelection.value.forEach(item => {
      ids.push(item.id)
    })
    deleteOreer(ids.join(","))
  }

}
// 查看订单
const selectOrder = (id: number) => {
  router.push({
    path: "orderDetail",
    query: { id }
  })
}
// 订单发货
const sendOrder = (row: IOrderDeliveryParamsModel | { deliveryCompany: string, deliverySn: string, id: number }[]) => {
  let newRow = [] as any
  if (Array.isArray(row)) {
    newRow = row.map(item => {
      return {
        deliveryCompany: item.deliveryCompany,
        deliverySn: item.deliverySn,
        orderId: item.id
      }
    })
  } else {
    newRow.push(row)
  }
  ElMessageBox.confirm("确定要发货吗？", "发货提示", {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    order.sendOrder(newRow).then(res => {
      if (res.code === 200) {
        ElMessage.success("发货成功")
      } else {
        ElMessage.error(res.message)
      }
    }).finally(() => {
      getAdminList()
    })
  }).catch(() => {
    ElMessage.success("已取消发货")
  })

}
// 批量关闭订单
const orderId = ref()
const closeOrderByIds = (ids: number | number[]) => {
  console.log(ids);
  if (Array.isArray(ids)) {
    closeIds.value = ids
  } else {
    orderId.value = ids
  }
  openCloseOrder()
}
const closeOrderVisiable = ref(false)
// 打开关闭订单页面
const openCloseOrder = () => {
  closeOrderVisiable.value = true
}
const closeOpenOrderVisiable = () => {
  closeOrderVisiable.value = false
}
// 删除订单
const deleteOreer = (id: number | number[] | string) => {
  ElMessageBox.confirm("您确定要删除该订单？", "删除提示", {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    order.deleteOrder({ ids: id }).then(res => {
      if (res.code === 200) {
        ElMessage.success("删除订单成功")
      } else {
        ElMessage.error("删除订单失败")
      }
    }).finally(() => {
      getAdminList()
    })
  }).catch(() => {
    ElMessage.success("已取消删除该订单")
  })
}
// 订单跟踪
const times = ref()
const orderTrackVis = ref(false)
const openOrderTrack = () => {
  orderTrackVis.value = true
}
const closeOrderTrack = () => {
  orderTrackVis.value = false
}
watch(() => searchOrderForm.value, () => {
  times.value = searchOrderForm.value.createTime
})
</script>

<style lang="less" scoped>
:deep(.el-table .cell) {
  text-align: center;
}

// 阴影
.el-table,
.search {
  box-shadow: 2px 3px 11px -5px;
}

// 筛选搜索
.search {
  box-shadow: 2px 3px 11px -5px;
  padding: 20px;
  margin-bottom: 30px;
}

.search_top {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .search_top_left {

    display: flex;
    align-items: center;

    .el-icon {
      margin-right: 6px;
    }
  }
}

// 表单
.peo {
  padding-left: 13px;
}

.pag {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .left_more {
    display: flex;
    align-items: center;

    .el-select {
      margin-right: 8px;
    }
  }
}

.el-table {
  margin-bottom: 20px;
}
</style>